<?php
namespace app\index\controller;
use app\model\Agent as AgentModel;
use app\model\AgentForm as AgentFormModel;
use think\Db;


class Agent extends Base
{
    // public $exception = ['index','register','detail'];

    public function __construct(){
        $model = new AgentModel();
        $this->model = $model;
        parent::__construct();
        
        $page_info = $this->page_info;
        $page_info['title'] = '活动';

        $this->assign([
            'model'=>$this->model,
            'page_info'=>$page_info
        ]);
    }

    
    public function form(){
        $map_params = [
            ['key'=>'truename','type'=>'like'],
            ['key'=>'mobile','type'=>'like'],
            ['key'=>'status','type'=>'='],
        ];
        $map = getSearchParam($map_params);

        $page_param = [
            'page'=>input('page',1),
            'list_rows'=>input('page_size',20)
        ];
        // 显示筛选
        $search_params = [
            [
                ['key'=>'truename','name'=>'姓名','type'=>'text'],
                ['key'=>'mobile','name'=>'手机','type'=>'text'],
            ]
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);

        $ulogin = $this->login_user;
        $data = Db::name('agent')->where('user_id',$ulogin['id'])->find();
        if (empty($data)) {
            return redirect(url('register'));
        }
        $map[] = ['agent_id','=',$data['id']];

        $list = Db::name('agent_form')->where($map)->order('id','desc')->paginate($page_param);
        $page = $list->render();
        $list = $list->toarray();
        foreach ($list['data'] as $k => $vo) {
            
        }
        return view('form', [
            'list'=>$list,
            'page'=>$page
        ]);
    }

    public function gongzhong(){
       
        return view('gongzhong', [
  
        ]);
    }

    public function export(){
        $model = new AgentFormModel();
        $map_params = [
            ['key'=>'truename','type'=>'like'],
            ['key'=>'mobile','type'=>'like'],
            ['key'=>'status','type'=>'='],
        ];
        $map = getSearchParam($map_params);

        $list = $model->where($map)->order('id','asc')->select();
        $list = $list->toarray();
        foreach ($list as $k => $vo) {
  
        }

        $data = [];
        $title = ['姓名', '手机','邮箱','公司名称','需求&建议','提交时间'];
        foreach ($list as $k => $vo) {
            $tmp = [
                $vo['truename'],$vo['mobile'],$vo['email'],$vo['company'],
                $vo['remark'],
                timeDef($vo['ctime'])
            ];

            foreach ($tmp as $t_k => $t_v) {
                $tmp[$t_k] = str_replace([',',"\n","\r"], '，', $t_v);
            }
            $data[] = $tmp;
        }

        exportCsv(date('YmdHis'),$title,$data);
    }

    public function assignFields(){
        $model = $this->model;

        $categorys = Db::name('wx_member_category')->select();
        $categorys = arrayParamExtract($categorys,'id','name');

        $assistants = Db::name('wx_assistant')->select();
        $assistants = arrayParamExtract($assistants,'id','name');

        $users = Db::name('user')->select();
        $users = arrayParamExtract($users,'id','nickname');

        $fields = [
            'name'=>['name'=>'名称','type'=>'text','valids'=>['required']],
            'image'=>['name'=>'图片','type'=>'file','url'=>url('base/upload')],
            'description'=>['name'=>'简介','type'=>'textarea'],
            'greet'=>['name'=>'欢迎语','type'=>'textarea'],
        ];
        $valids = createPageValid($fields);
        $this->assign([
            'fields'=>$fields,
            'valids'=>$valids
        ]);

    }

    public function assignSearchs(){
        $model = $this->model;
        $search_params = [
            [
                ['key'=>'name','name'=>'名称','type'=>'text'],
            ]
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);
    }

    public function index(){
        $ulogin = $this->login_user;
        $model = $this->model;
        $data = $model->where('user_id',$ulogin['id'])->find();
        if (empty($data)) {
            return redirect(url('register'));
        }

        $sessions = Db::name('agent_session')->where('agent_id',$data['id'])->select();
        foreach ($sessions as $k => $vo) {
            $msg = Db::name('agent_msg')->where('session_sn',$vo['session_sn'])->order('id','desc')->find();
            $msg['ctime'] = date('y-m-d H:i',$msg['ctime']);
            $sessions[$k]['msg'] = $msg;
        }


        return view('index', [
            'data'=>$data,
            'sessions'=>$sessions
        ]);
    }


    public function detail(){
        $ulogin = $this->login_user;
        $model = $this->model;
        $data = $model->where('user_id',$ulogin['id'])->find();
        if (empty($data)) {
            return redirect(url('register'));
        }
        return view('detail', [
            'data'=>$data
        ]);
    }

    public function register(){
        $ulogin = $this->login_user;
        $model = $this->model;

        if ($model->where('user_id',$ulogin['id'])->count() > 0) {
            return redirect(url('detail'));
        }
        if (request()->isPost()) {
            $fields = [
                'must'=>['name','image','description'],
                'nomust'=>['greet']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
            $save_data['ctime'] = time();
            $save_data['user_id'] = $ulogin['id'];

            if ( $id = $model->insertGetId($save_data) ) {
                $this->success("添加成功",url('detail'));
            }else{
                $this->error("添加失败");
            }
        }

        $this->assignFields();
        return view('register', [
            
        ]);
    }

    public function edit(){
        $ulogin = $this->login_user;
        $model = $this->model;
        
        
        if (request()->isPost()) {
            $fields = [
                'must'=>['name','image','description'],
                'nomust'=>['greet']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }

            if ( $model->where('user_id',$ulogin['id'])->update($save_data) ) {
                $this->success("修改成功",url('detail'));
            }else{
                $this->error("修改失败");
            }
        }

        $this->assignFields();
        $data = $model->where('user_id',$ulogin['id'])->find();
        if (empty($data)) {
            return redirect(url('register'));
        }
        return view('register', [
            'data'=>$data
        ]);


    }




   
}
